package com.example.hrsystem.ui.approval.overtime;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;

import com.example.hrsystem.R;
import com.example.hrsystem.workflow.ApprovalUtils;
import com.example.hrsystem.workflow.ApprovalViewModel;
import com.example.hrsystem.workflow.model.OvertimeRequest;

import java.util.Calendar;
import java.util.Date;

/**
 * 加班申请表单Activity
 * 用于用户填写和提交加班申请
 */
public class OvertimeRequestFormActivity extends AppCompatActivity {
    private ApprovalViewModel viewModel;
    private Spinner overtimeTypeSpinner;
    private Button dateButton;
    private Button startTimeButton;
    private Button endTimeButton;
    private TextView hoursTextView;
    private EditText reasonEditText;
    private Button submitButton;
    private ProgressBar progressBar;
    
    private Calendar calendar = Calendar.getInstance();
    private Date overtimeDate;
    private Date startTime;
    private Date endTime;
    
    private int currentUserId = 1000; // 默认用户ID，实际应用中应从登录信息获取
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_overtime_request_form);

        // 初始化ViewModel
        viewModel = new ViewModelProvider(this).get(ApprovalViewModel.class);

        // 初始化UI组件
        initUI();

        // 设置按钮点击事件
        setupButtonListeners();

        // 观察提交结果
        observeSubmitResult();
    }

    /**
     * 初始化UI组件
     */
    private void initUI() {
        overtimeTypeSpinner = findViewById(R.id.overtime_type_spinner);
        dateButton = findViewById(R.id.overtime_date_button);
        startTimeButton = findViewById(R.id.start_time_button);
        endTimeButton = findViewById(R.id.end_time_button);
        hoursTextView = findViewById(R.id.hours_text_view);
        reasonEditText = findViewById(R.id.reason_edit_text);
        submitButton = findViewById(R.id.submit_button);
        progressBar = findViewById(R.id.progress_bar);
        
        // 设置默认日期为今天
        overtimeDate = new Date();
        dateButton.setText(ApprovalUtils.formatDate(overtimeDate));
        
        // 设置默认时间
        calendar.setTime(overtimeDate);
        calendar.set(Calendar.HOUR_OF_DAY, 18);
        calendar.set(Calendar.MINUTE, 0);
        startTime = calendar.getTime();
        startTimeButton.setText(ApprovalUtils.formatTime(startTime));
        
        calendar.add(Calendar.HOUR_OF_DAY, 2);
        endTime = calendar.getTime();
        endTimeButton.setText(ApprovalUtils.formatTime(endTime));
        
        // 计算并显示默认时长
        updateHours();
    }

    /**
     * 设置按钮点击事件
     */
    private void setupButtonListeners() {
        // 加班日期选择
        dateButton.setOnClickListener(v -> showDatePicker());
        
        // 开始时间选择
        startTimeButton.setOnClickListener(v -> showStartTimePicker());
        
        // 结束时间选择
        endTimeButton.setOnClickListener(v -> showEndTimePicker());
        
        // 提交按钮
        submitButton.setOnClickListener(v -> submitOvertimeRequest());
    }

    /**
     * 显示日期选择器
     */
    private void showDatePicker() {
        Calendar calendar = Calendar.getInstance();
        if (overtimeDate != null) {
            calendar.setTime(overtimeDate);
        }
        
        DatePickerDialog datePickerDialog = new DatePickerDialog(
                this,
                (view, year, month, dayOfMonth) -> {
                    Calendar selectedCalendar = Calendar.getInstance();
                    selectedCalendar.set(year, month, dayOfMonth);
                    overtimeDate = selectedCalendar.getTime();
                    dateButton.setText(ApprovalUtils.formatDate(overtimeDate));
                    
                    // 重新计算时长
                    updateHours();
                },
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH)
        );
        
        datePickerDialog.show();
    }

    /**
     * 显示开始时间选择器
     */
    private void showStartTimePicker() {
        Calendar calendar = Calendar.getInstance();
        if (startTime != null) {
            calendar.setTime(startTime);
        }
        
        TimePickerDialog timePickerDialog = new TimePickerDialog(
                this,
                (view, hourOfDay, minute) -> {
                    Calendar selectedCalendar = Calendar.getInstance();
                    selectedCalendar.setTime(overtimeDate);
                    selectedCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
                    selectedCalendar.set(Calendar.MINUTE, minute);
                    startTime = selectedCalendar.getTime();
                    startTimeButton.setText(ApprovalUtils.formatTime(startTime));
                    
                    // 重新计算时长
                    updateHours();
                    
                    // 如果结束时间早于开始时间，自动调整结束时间
                    if (endTime.before(startTime)) {
                        Calendar endCalendar = Calendar.getInstance();
                        endCalendar.setTime(startTime);
                        endCalendar.add(Calendar.HOUR_OF_DAY, 1);
                        endTime = endCalendar.getTime();
                        endTimeButton.setText(ApprovalUtils.formatTime(endTime));
                    }
                },
                calendar.get(Calendar.HOUR_OF_DAY),
                calendar.get(Calendar.MINUTE),
                true
        );
        
        timePickerDialog.show();
    }

    /**
     * 显示结束时间选择器
     */
    private void showEndTimePicker() {
        Calendar calendar = Calendar.getInstance();
        if (endTime != null) {
            calendar.setTime(endTime);
        }
        
        TimePickerDialog timePickerDialog = new TimePickerDialog(
                this,
                (view, hourOfDay, minute) -> {
                    Calendar selectedCalendar = Calendar.getInstance();
                    selectedCalendar.setTime(overtimeDate);
                    selectedCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
                    selectedCalendar.set(Calendar.MINUTE, minute);
                    endTime = selectedCalendar.getTime();
                    endTimeButton.setText(ApprovalUtils.formatTime(endTime));
                    
                    // 重新计算时长
                    updateHours();
                    
                    // 验证结束时间是否晚于开始时间
                    if (endTime.before(startTime)) {
                        Toast.makeText(this, "结束时间不能早于开始时间", Toast.LENGTH_SHORT).show();
                        // 恢复原结束时间
                        endTimeButton.setText(ApprovalUtils.formatTime(calendar.getTime()));
                    }
                },
                calendar.get(Calendar.HOUR_OF_DAY),
                calendar.get(Calendar.MINUTE),
                true
        );
        
        timePickerDialog.show();
    }

    /**
     * 更新加班时长
     */
    private void updateHours() {
        if (startTime != null && endTime != null) {
            double hours = ApprovalUtils.calculateHours(startTime, endTime);
            hoursTextView.setText(String.format("%.1f小时", hours));
        }
    }

    /**
     * 提交加班申请
     */
    private void submitOvertimeRequest() {
        // 表单验证
        if (!validateForm()) {
            return;
        }
        
        // 创建加班申请对象
        OvertimeRequest overtimeRequest = new OvertimeRequest();
        
        // 设置基本信息
        overtimeRequest.setApplicantId(currentUserId);
        overtimeRequest.setCreatedAt(new Date());
        overtimeRequest.setUpdatedAt(new Date());
        overtimeRequest.setStatus("PENDING");
        
        // 设置加班信息
        overtimeRequest.setOvertimeType(overtimeTypeSpinner.getSelectedItem().toString());
        overtimeRequest.setOvertimeDate(overtimeDate);
        overtimeRequest.setStartTime(startTime);
        overtimeRequest.setEndTime(endTime);
        overtimeRequest.setHours((float)ApprovalUtils.calculateHours(startTime, endTime));
        overtimeRequest.setReason(reasonEditText.getText().toString().trim());
        
        // 设置审批人ID（简化处理，实际应该从部门信息或选择界面获取）
        int approverId = 2000; // 假设默认审批人ID为2000
        
        // 提交申请
        viewModel.submitOvertimeRequest(overtimeRequest, approverId);
    }

    /**
     * 验证表单
     */
    private boolean validateForm() {
        // 验证必填字段
        if (reasonEditText.getText().toString().trim().isEmpty()) {
            Toast.makeText(this, R.string.reason_required, Toast.LENGTH_SHORT).show();
            return false;
        }
        
        // 验证时间范围
        if (startTime == null || endTime == null || endTime.before(startTime)) {
            Toast.makeText(this, R.string.invalid_date_range, Toast.LENGTH_SHORT).show();
            return false;
        }
        
        return true;
    }

    /**
     * 观察提交结果
     */
    private void observeSubmitResult() {
        // 观察加载状态
        viewModel.getIsLoading().observe(this, isLoading -> {
            if (isLoading) {
                progressBar.setVisibility(View.VISIBLE);
                submitButton.setEnabled(false);
            } else {
                progressBar.setVisibility(View.GONE);
                submitButton.setEnabled(true);
            }
        });
        
        // 观察提交成功
        viewModel.getOperationSuccess().observe(this, isSuccess -> {
            if (isSuccess != null && isSuccess) {
                Toast.makeText(this, R.string.leave_request_submit_success, Toast.LENGTH_SHORT).show();
                finish(); // 提交成功后返回上一页
            }
        });
        
        // 观察错误信息
        viewModel.getErrorMessage().observe(this, errorMessage -> {
            if (errorMessage != null && !errorMessage.isEmpty()) {
                Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT).show();
            }
        });
    }
}